package com.alibaba.citrus.cr.platform.enhance.facade.service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.crplatformenhance.goodsfavorites.dto.UpdateResponse;
import com.epoch.app.crplatformenhance.goodsfavorites.model.GoodsFavorites;
import com.epoch.app.crplatformenhance.goodsfavorites.service.GoodsFavoritesService;
import com.epoch.app.crplatformenhance.model.dto.GetTopOrganizationListRequest;
import com.epoch.app.crplatformenhance.model.dto.GoodsFavoriteGood;
import com.epoch.app.crplatformenhance.model.dto.GoodsFavoritesLoadListRequest;
import com.epoch.app.crplatformenhance.model.dto.ScItemManageRangeSearchRequest;
import com.epoch.app.crplatformenhance.model.enums.ScItemManageRangeStatus;
import com.epoch.app.crplatformenhance.scitemmanagerange.model.ScItemManageRange;
import com.epoch.app.crplatformenhance.scitemmanagerangeread.service.ScItemManageRangeReadService;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Primary
public class GoodsFavoritesServiceImpl implements GoodsFavoritesService {

    @Autowired
    private BcOrderService bcOrderService;
    @Resource
    private GoodsFavoritesService goodsFavoritesService;
    @Resource
    private ScItemManageRangeReadService scItemManageRangeReadService;
    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;
    private static final Integer COMPANY_TYPE = 103;
    private static final Integer SALE_ORG_TYPE = 104;

    @Override
    public Result<Boolean> updateOrInsertFavorites(GoodsFavorites goodsFavorites){
        if (Objects.isNull(goodsFavorites)) {
            return Result.fail("OTS-01-005-02-15-015","更新或新增收藏夹不能为空!");
        }
        EmployeeGetCurrentLoginResponse employee = bcOrderService.employeeGetCurrentLogin();

        if (Objects.isNull(employee)||Objects.isNull(employee.getEmployeeId())){
            return Result.fail("OTS-01-005-02-15-017","货品收藏夹更新或新增,获取当前登陆人信息错误!");
        }

        goodsFavorites.setUserId(employee.getEmployeeId());
        goodsFavorites.setUpdaterId(employee.getEmployeeId());

        //创建还是根据通过当前登录人查询
        GoodsFavoritesLoadListRequest loadListRequest = new GoodsFavoritesLoadListRequest();
        loadListRequest.setUserId(employee.getEmployeeId().replace("CZ_",""));
        Result<List<GoodsFavorites>> listResult = goodsFavoritesService.loadList(loadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            //insert operate
            goodsFavorites.setCreatorId(employee.getEmployeeId());
            create(goodsFavorites);
            return Result.success(Boolean.TRUE);
        }
        goodsFavorites.setId(listResult.getResult().get(0).getId());

//        if (Objects.isNull(goodsFavorites.getId())) {
//            //insert operate
//            goodsFavorites.setCreatorId(employee.getEmployeeId());
//            create(goodsFavorites);
//            return Result.success(Boolean.TRUE);
//        }

        //or update
        goodsFavorites.setCreatorId(employee.getEmployeeId());
        UpdateResponse update = update(goodsFavorites);
        if (Objects.nonNull(update)&&Objects.nonNull(update.getCount())&&update.getCount()>0){
            return Result.success(Boolean.TRUE);
        }
        return Result.fail("OTS-01-005-02-15-016","数据更新失败!");
    }

    //预报销售专用收藏夹
    @Override
    @FacadeInvoker
    public Result<List<GoodsFavorites>> queryGoodsFavoritesForForecastSale() {
        EmployeeGetCurrentLoginResponse employee = bcOrderService.employeeGetCurrentLogin();
        if (employee == null || employee.getEmployeeId() == null){
            return Result.success(null);
        }
        GoodsFavoritesLoadListRequest loadListRequest = new GoodsFavoritesLoadListRequest();
        String userId = employee.getEmployeeId().replace("CZ_","");
        if (StringUtils.isBlank(userId)){
            return Result.success(null);
        }
        loadListRequest.setUserId(userId);
        loadListRequest.setLimit(10);
        Result<List<GoodsFavorites>> listResult = goodsFavoritesService.loadList(loadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            return Result.success(null);
        }
        List<ScItemManageRange> scItemManageRanges = searchScItemManageRange();
        if (CollectionUtils.isEmpty(scItemManageRanges)){
            return listResult;
        }
        List<GoodsFavorites> goodsFavorites = listResult.getResult();
        //如果出现多个销售组织
        boolean allDisabled = scItemManageRanges.stream().allMatch(scItemManageRange -> ScItemManageRangeStatus.DISABLED.getValue().equals(scItemManageRange.getStatus()));
        if (!allDisabled){
            Map<String, List<ScItemManageRange>> saleOrgId2RangeMap = scItemManageRanges.stream().collect(Collectors.groupingBy(ScItemManageRange::getSaleOrgId));
            //如果有多个销售组织
            if (saleOrgId2RangeMap.size() > 1){
                //移除某个组织全部禁用的
                saleOrgId2RangeMap.values().forEach(ranges -> {
                    boolean disabled = ranges.stream().allMatch(x -> ScItemManageRangeStatus.DISABLED.getValue().equals(x.getStatus()));
                    if (disabled){
                        scItemManageRanges.removeAll(ranges);
                    }
                });
            }
            goodsFavorites = listResult.getResult().stream().filter(favorites ->
            {
                if (StringUtils.isBlank(favorites.getGoodsList())){
                    return false;
                }
                List<GoodsFavoriteGood> goods = JSON.parseArray(favorites.getGoodsList(),GoodsFavoriteGood.class);
                if (CollectionUtils.isEmpty(goods)){
                    return false;
                }
                List<GoodsFavoriteGood> filteredGoods = goods.stream().filter(goodsFavoriteGood -> scItemManageRanges.stream().anyMatch(scItemManageRange ->
                                Objects.equals(goodsFavoriteGood.getId(),scItemManageRange.getScItemId()) &&
                                        ScItemManageRangeStatus.ENABLE.getValue().equals(scItemManageRange.getStatus())))
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(filteredGoods)){
                    favorites.setGoodsList(JSON.toJSONString(filteredGoods));
                    return true;
                }
                return false;
            }).collect(Collectors.toList());
            listResult.setResult(goodsFavorites);
        }
        return listResult;
    }


    private List<ScItemManageRange> searchScItemManageRange(){
        Result<List<ScItemManageRange>> search = scItemManageRangeReadService.searchWithPermission();
        return Optional.ofNullable(search).map(Result::getResult).orElse(null);
    }
}
